﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using In.Api.Dto.Notify;
using InDbContext;
using Newtonsoft.Json;
using Quartz;
using Rmq.Center;
using RefundInfo = In.Api.Dto.Notify.Notification.RefundInfo;

namespace In.TaskRunner.QuartzJobs
{
    public class RefundInfoJob: IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(RefundInfoJob));

        public void Execute(IJobExecutionContext context)
        {
            var connstr = ConfigurationManager.ConnectionStrings["HISNoticeEntity"].ConnectionString;
            var connection = new OdbcConnection(connstr);
            connection.Open();
            string sql = "select RowId, RefundType, PatientId,RefundTime, SumFee, OrderId,ClinicNo from RefundInfo where RowNum<10";
            var adapter = new OdbcDataAdapter(sql, connection);
            try
            {
                var dt = new DataTable();
                adapter.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    Console.WriteLine("找到{0}条退款通知", dt.Rows.Count);
                }

                using (var ctx = new HospDatabaseEntity())
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        var rowId = dr["RowId"].ToString();
                        var patientId = dr["PatientId"].ToString();
                        var patient = ctx.HospCards.FirstOrDefault(card => card.PatientId == patientId);
                        if (patient != null)
                        {
                            var refundInfo = new RefundInfo();
                            refundInfo.RefundType = dr["RefundType"].ToInt32();
                            refundInfo.PatientId = dr["PatientId"].ToString();
                            refundInfo.Name = patient.Name;
                            refundInfo.CardNo = patient.CardNo;
                            if (dr["RefundTime"].IsDBNull())
                            {
                                refundInfo.RefundTime = null;
                            }
                            else
                            {
                                refundInfo.RefundTime = dr["RefundTime"].ToDateTime();
                            }
                            refundInfo.SumFee = dr["SumFee"].ToDecimal();
                            if (dr["OrderId"] != null)
                            {
                                refundInfo.OrderId = dr["OrderId"].ToString();
                            }
                            else
                            {
                                refundInfo.OrderId = "";
                            }
                            if (dr["ClinicNo"] != null)
                            {
                                refundInfo.ClinicNo = dr["ClinicNo"].ToString();
                            }
                            else
                            {
                                refundInfo.ClinicNo = "";
                            }
                            ProcessNotice(refundInfo);
                            
                        }
                        DeleteNotice(rowId);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(JsonConvert.SerializeObject(ex));
                Logger.ErrorFormat("RefundInfoJob出错：{0}", ex.Message);
            }
            adapter.Dispose();
            connection.Close();
            connection.Dispose();
        }


        private static readonly HttpClient HttpClient = new HttpClient();

        private void ProcessNotice(RefundInfo refundInfo)
        {
            var notification = new NotificationRequest()
            {
                NotificationType = "RefundNotice",
                NotificationInfo = JsonConvert.SerializeObject(refundInfo)
            };
            Console.WriteLine("退款通知:{0}", notification.NotificationInfo);

            try
            {

                var hospMessageProducer = new HospMessageProducer();
                hospMessageProducer.Publish(new HospMessageMsg()
                {
                    NotificationType = notification.NotificationType,
                    NotificationInfo = notification.NotificationInfo
                });

                //HttpClient.PostAsJsonAsync(alipayApiAddress, notification);
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("发送退款通知出错：{0}", e.Message);
            }
        }

        private void DeleteNotice(string rowId)
        {
            var connstr = ConfigurationManager.ConnectionStrings["HISNoticeEntity"].ConnectionString;
            OdbcConnection connection = new OdbcConnection(connstr);
            connection.Open();
            string sql = string.Format("delete from RefundInfo where RowId=?");
            var cmd = new OdbcCommand(sql, connection);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add(new OdbcParameter("@RowId", rowId));
            cmd.ExecuteNonQuery();
            connection.Close();
            connection.Dispose();
            //Notify(ServiceStatus.BUSY, "已经删除了一条退款通知");
        }
    }
}
